package controller

import (
	"bytes"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"imooc.com/demo_pms/comm"
	"imooc.com/demo_pms/conf"
	"imooc.com/demo_pms/services"
	"imooc.com/demo_pms/web/template"
	"imooc.com/demo_pms/web/utils"
	"io/ioutil"
	"os"
)

type UserInfoController struct {
	// 记得 Ctx 要大写，不然无法引用，因为这错误耽误了多少时间
	Ctx         iris.Context
	UserService services.UserService
	PayService  services.PayrollService
}

/*
type View struct {
	Name   string  //文件名，如 hello/index.html
	Layout string  //布局
	Data   interface{} // map or a custom struct.  //数据
	Code   int     //错误码
	Err    error   //err
}*/

func (a *UserInfoController) GetLogin() mvc.Result {
	// 验证帐号密码
	username := a.Ctx.FormValueDefault("username", "")
	pwd := a.Ctx.FormValueDefault("password", "")

	// 成功进入搜索页面，失败重新返回搜索页面
	if username == conf.AdminUser && pwd == conf.AdminPWD {
		return mvc.View{
			Name: "search.html",
		}
	} else {
		return mvc.View{
			Name: "login.html",
			Data: map[string]string{
				"title": "人事档案管理后台登陆",
				"msg":   "帐号密码错误，请重新输入",
			},
		}
	}
}

func (a *UserInfoController) GetSearch() mvc.Result {
	// 解析表格参数并生成相应的sql，查询结果，转换为html结果返回
	sql := utils.ParamString(a.Ctx)
	datalist, err := a.UserService.Query(sql)
	if err != nil {
		return mvc.View{
			Name: "search.html",
			Err:  err,
		}
	}
	if len(datalist) < 1 {
		return mvc.View{
			Name: "search.html",
		}
	} else {
		//  将datalist转换为html返回去
		rsList := comm.SliceMapToSliceString(datalist)
		buf := new(bytes.Buffer)
		template.UserList(rsList, buf)
		return mvc.Response{
			Text: buf.String(),
		}
	}
}

func (a *UserInfoController) PostDownload() {
	sql := utils.ParamString(a.Ctx)
	dataList, err := a.UserService.Query(sql)
	if err != nil {
		a.Ctx.WriteString("internal error ")
		return
	}

	if len(dataList) < 1 {
		a.Ctx.WriteString("给定的条件查询不出结果")
		return
	}
	file := comm.SliceMapToExcel(dataList)
	err = file.SaveAs("./tmp/tmp.xlsx")
	if err != nil {
		a.Ctx.WriteString("internal error ")
		return
	}
	f, err := os.Open("./tmp/tmp.xlsx")
	if err != nil {
		a.Ctx.WriteString("internal error ")
		return
	}
	defer f.Close()

	out, err := ioutil.ReadAll(f)
	if err != nil {
		a.Ctx.WriteString("internal error ")
		return
	}

	a.Ctx.Header("Content-Disposition",
		`attachment; filename="tmp.xlsx"`)
	a.Ctx.Write(out)
}
